package com.study.util;

import java.io.File;
import java.io.FileInputStream;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

import redis.clients.jedis.Jedis;

public class RedisSerFile {
	
	private static RuntimeSchema<File> schema = RuntimeSchema.createFrom(File.class);

	public static void main(String[] args) throws Exception {
		
		File file = new File("C:/soft/aa.txt");
		long length = file.length();
		System.out.println("length:" + length);
		int timeout = 5*60;
		//将user对象存入redis
		String result = putUser(file,timeout);
		System.out.println("返回结果：" + result);
		
		File file1 = getUser(1);
		FileInputStream fis = new FileInputStream(file1);
		byte[] bytes = new byte[fis.available()];
		fis.read(bytes);
		fis.close();
		System.out.println(new String(bytes, "gbk"));
	}
	
	public static String putUser(File file,int timeout) {
		String result = "";
		try {
			Jedis jedis = RedisUtil.getJedis();
			try {
				String key = "file:1";
				byte[] bytes = ProtostuffIOUtil.toByteArray(file, schema, 
						LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
				result = jedis.setex(key.getBytes(), timeout, bytes);
				return result;
			}finally {
				jedis.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static File getUser(int id) {
		try {
			Jedis jedis = RedisUtil.getJedis();
			try {
				String key = "file:"+id;
				byte[] bytes = jedis.get(key.getBytes());
				if(bytes != null && bytes.length>0) {
					File file = schema.newMessage();
					ProtostuffIOUtil.mergeFrom(bytes, file, schema);
					
					return file;
				}
			}finally {
				jedis.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
